<template>
  <div class="container">
    <!-- 条件查询 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="userQuery.name" placeholder="用户姓名"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <!--
          数据类型一定要和取出的json中的一致，否则没法回填
          因此，这里value使用动态绑定的值，保证其数据类型是number
        -->
        <el-select v-model="userQuery.status" placeholder="用户状态">
          <el-option label="正常" :value="0"></el-option>
          <el-option label="封禁" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="userQuery.usertype" placeholder="用户类型">
          <el-option label="普通用户" :value="0"></el-option>
          <el-option label="心理咨询师" :value="1"></el-option>
<!--          <el-option label="管理员" :value="2"></el-option>-->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-seacher" @click="getUserInfo()">查询</el-button>
        <el-button type="default" @click="resetData()">清空</el-button>
      </el-form-item>
    </el-form>

    <!--批量操作-->
    <div>
      <router-link :to="{name:'AddUser'}">
        <el-button type="primary" @clik="addUser" id="add-user-btn" size="medium">添加用户</el-button>
      </router-link>
      <el-button type="primary" @click="exportUserInfo" id="export-user-btn" size="medium">导出用户</el-button>
      <el-button type="danger" @click="deleteUserBatch" size="medium">删除选中</el-button>
    </div>

    <!--用户表格-->
    <div class="table-box" >
      <el-table :data="list" border
                style="width: 100%"
                :header-cell-style="headClass"
                :cell-style="rowClass"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="date"
                         label="序号"
                         width="50">
          <!--计算得出序号-->
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="account" label="用户名" width="120"> </el-table-column>
        <el-table-column prop="name" label="姓名" width="70"> </el-table-column>
        <el-table-column prop="gender" label="性别" width="70">
          <template #default="scope">
            {{ scope.row.gender===0?'男':'女'}}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="170"> </el-table-column>
        <el-table-column prop="lastLogin" sortable label="最后登录" width="160"> </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-switch active-color="#ff4949"
                       v-model="scope.row.status"
                       :active-value="1"
                       :inactive-value="0" @change="prohibitUser(scope.row.userId, scope.row.status)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="usertype" label="用户类型" width="120">
          <template #default="scope">
            <span v-if="scope.row.usertype===0">普通用户</span>
            <span v-if="scope.row.usertype===1">心理咨询师</span>
<!--            <span v-if="scope.row.usertype===2">管理员</span> 管理员不能看到其他管理员的信息-->
<!--            <span v-if="scope.row.usertype===3">超级管理员</span> 管理员不能看到超级管理员的信息-->
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <router-link :to="{name:'UserDetail', params:{id: scope.row.userId}}">
              <el-button size="medium" icon="el-icon-edit" id="view-btn">查看</el-button>
            </router-link>
            <el-button
                size="medium"
                type="danger"
                @click="deleteUserById(scope.row.userId)" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页  -->
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getUserInfo"
    />
    <!-- @current-change="getTeacherList" 即调用getUserInfo方法，并且自动传入参数page(页数) -->
  </div>

</template>

<script>
import user from '@/api/admin/admin'

export default {
  data() {
    return {
      list: null,
      pageSize: 10,
      currentPage: 1,
      total: 0,
      // 查询条件
      userQuery: {
        name: '',
        roleName: '',
        status: null,
        usertype: null,
      },
      // 选中用户信息
      multipleSelection: [],
      // 选中用户编号
      userIdSelected: [],
      flag: true,
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    // 表头居中显示
    headClass() {
      return "text-align:center"
    },
    rowClass() {
      return "text-align:center"
    },
    init() {
      this.getUserInfo()
    },
    getUserInfo(currentPage = 1) {
      this.currentPage = currentPage
      user.getUserInfo(this.currentPage, this.pageSize, this.userQuery)
          .then((response) => {
            this.list = response.data.item.records;
            this.total = response.data.item.total;
          }).catch(error => {
        console.log(error);
        this.$message({
          type: 'error',
          message: '获取用户信息失败'
        })
      })
    },
    // 重置搜索栏
    resetData() {
      this.userQuery.status = null;
      this.userQuery.roleName = null;
      this.userQuery.name = null;
      this.userQuery.usertype = null;
    },
    // 当选中发生变化时，将用户编号放入userIdSelected
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.userIdSelected = [];
      let id = null;
      for (let i = 0; i < this.multipleSelection.length; i++) {
        id = this.multipleSelection[i].userId
        this.userIdSelected[i] = id
      }
    },
    // 删除用户
    deleteUserById(id) {
      this.$confirm('此操作将删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        user.deleteUserById(id).then(response => {
          this.init();
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          return response;
        }).catch((response) => {
          console.log("error: " + response.message)
        })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 批量删除用户
    deleteUserBatch() {
      this.$confirm('此操作将删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let array = [];
        for (let i = 0; i < this.userIdSelected.length; i++) {
          let Id = {};
          Id.id = this.userIdSelected[i]
          array[i] = Id
        }
        array = {array};
        user.deleteUserBatch(array).then(response => {
          this.init();
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          return response;
        }).catch((response) => {
          console.log("error: " + response.message)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        })
      })
    },
    // 导出用户信息exportUserInfo
    exportUserInfo() {
      this.$confirm('此操作将导出用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (this.userIdSelected.length === 0){
          this.$message({
            type: 'info',
            message: '请勾选用户',
          })
          return ;
        }
        let array = [];
        for (let i = 0; i < this.userIdSelected.length; i++) {
          let Id = {};
          Id.id = this.userIdSelected[i]
          array[i] = Id
        }
        array = {array};
        user.exportUserInfo(array).then(response => {
          const content = response
          const blob = new Blob([content])
          const fileName = '用户信息表格.xlsx'
          if('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }

          this.multipleSelection = []

          this.$message({
            type: 'success',
            message: '导出成功!',
          })

        }).catch((response) => {
          console.log("error: " + response.message)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出',
        })
      })
    },
    // 封禁或激活用户
    prohibitUser(id, status) {
      status = !status;
      let s = 0
      if (status) {
        s = 1
      } else {
        s = 0
      }
      user.prohibitUser(id, s).then(response => {
        let msg = ""
        if (status) {
          msg = "激活成功"
        } else {
          msg = "封禁成功"
        }
        this.$message({
          type: 'success',
          message: msg,
        })
        return response;
      }).catch(response => {
        console.log(response.message)
        this.$message({
          type: 'error',
          message: "操作失败",
        })
      })
    },
    addUser() {
      this.$router.push("/admin/userDetail")
    },

  }


}
</script>

<style>
  .table-box {


  }

  .container {
    /*边界 20px*/
    margin: 20px;
  }

  .batch-btn {
    margin-bottom: 20px;
  }
  #view-btn {
    margin-right: 20px;
  }
  #add-user-btn {
    margin-right: 20px;
  }
  #export-user-btn {
    margin-right: 11px;
  }
</style>
